package com.yxp.middle;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther     : yxpweb
 * @Date       : 2021/3/15 18:17
 * @Description: 54. 螺旋矩阵
 */
public class Problem54 {

    public static void main(String[] args) {
        Problem54 problem54 = new Problem54();
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        List<Integer> list = problem54.spiralOrder(matrix);
        System.out.println(list);

    }

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resultList = new ArrayList<>();
        int height = matrix.length - 1;
        int width = matrix[0].length - 1;

        int maxV = height >= width ? height : width;
        int count = maxV / 2 + 1;

        for (int i = 0; i < count; i++) {
            for (int j = i; j <= width - i; j++) {
                resultList.add(matrix[i][j]);
            }
            for (int j = i + 1; j <= height - i; j++) {
                resultList.add(matrix[j][width - i]);
            }
            for (int j = width - (i + 1); j >= i && (height - i != i); j--) {
                resultList.add(matrix[height - i][j]);
            }
            for (int j = height - (i + 1); j >= i + 1 && (width - i) != i; j--) {
                resultList.add(matrix[j][i]);
            }
        }
        return resultList;
    }
}
